//
//  ClassifyViewController.m
//  GoBigMarket
//
//  Created by legend on 16/8/15.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "ClassifyViewController.h"
#import "SearchViewController.h"
#import "RightTableViewCell.h"
#import "StoreViewController.h"
#import "CommodityViewController.h"
#import "ClassIfModel.h"
#import "ClassIfCell.h"
#import "ClassIfProductModel.h"
#import "AddressViewController.h"
#import "WelcomViewController.h"

static float rightTop;//右侧tableView的上坐标
static BOOL isFirst = YES;
static NSIndexPath *selIndexPath;
static float rightHeight;//原本右侧tableView的高度
static NSInteger oldShopId;//保存之前的shopId

@interface ClassifyViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    SearchViewController *_searchVC;
}
@property (weak, nonatomic) IBOutlet UIButton *marketBtn;
@property (strong, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UIButton *storeBtn;
@property (nonatomic,strong)NSIndexPath *indexPath;
@property (nonatomic,strong)StoreViewController *storeViewCollection;
@property (nonatomic,strong)CommodityViewController *commodityVC;
@property (nonatomic,strong)NSMutableArray *classArr;//分类名数据源
@property (nonatomic,strong)NSMutableArray *twoClassArr;//二级分类数据源
@property (nonatomic,strong)NSMutableArray *productArr;//产品model数组
//当商店id为空时显示
@property (nonatomic,strong)UIImageView *zeroBackIamgeView;
@end

@implementation ClassifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    if (!_classArr) {
        self.classArr = [NSMutableArray array];
    }
    if (!_twoClassArr) {
        _twoClassArr = [NSMutableArray array];
    }
    
    if (!_productArr) {
        _productArr = [NSMutableArray array];
    }

    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.showsHorizontalScrollIndicator = NO;
//    self.rightTableView.bottom = XNWindowHeight - 49;
    
    UIButton *btn = [UIButton buttonWithType:0];
    [btn setImage:[UIImage imageNamed:@"分类搜索"] forState:0];
    [btn setTitle:@"sousuo" forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 25, 25);
    [btn addTarget:self action:@selector(searchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
}
#pragma mark - 搜索页面入口
//点击搜索栏，弹出搜索页面
- (IBAction)searchBtnAction:(id)sender {
    if (!_searchVC) {
        _searchVC = [[SearchViewController alloc]init];
    }
    [self.navigationController pushViewController:_searchVC animated:NO];
}
#pragma mark - 地址页面
- (void)addressBtnClick{
//    AddressViewController *addressVC = [[AddressViewController alloc]init];
//    [self.navigationController pushViewController:addressVC animated:YES];
}
#pragma mark - 生命周期
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //存储右侧tableView的高度
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:GETLeftAddress style:UIBarButtonItemStylePlain target:self action:@selector(addressBtnClick)];
    
//    isFirst = YES;
    self.tabBarController.tabBar.hidden = NO;
    //判断有木有商店id
    if (!GETShopId) {
        [self.classArr removeAllObjects];
        oldShopId = -1;
        self.marketBtn.hidden = YES;
        self.hotBtnView.hidden = YES;
        self.rightTableView.hidden = YES;
        self.leftTableView.hidden = YES;
        if (!self.zeroBackIamgeView) {
            //使用占位图
            self.zeroBackIamgeView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,XNWindowWidth , XNWindowHeight - 49 - 64)];
            self.zeroBackIamgeView.image = [UIImage imageNamed:@"占位图"];
        }
        [self.view addSubview:_zeroBackIamgeView];
    }else{
//        self.hotBtnView.hidden = NO;
        [self viewDidLayoutSubviews];
        
        self.rightTableView.hidden = NO;
        self.leftTableView.hidden = NO;
        self.marketBtn.hidden = NO;
        [self.marketBtn setTitle:GETShopName forState:UIControlStateNormal];
        [self.zeroBackIamgeView removeFromSuperview];
        self.rightTableView.top = self.hotBtnView.bottom;
        [self netWorking];
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    rightHeight = self.leftTableView.height;
}
#pragma mark - 网络请求
//获取一级分类
- (void)netWorking{

//    if (oldShopId == [GETShopId integerValue]){
//        isFirst = NO;
//         [self.rightTableView reloadData];
//    }else{
//    isFirst = YES;
//    oldShopId = [GETShopId integerValue];
    [CQNetWorkTools GETWithURL:GetFenLei par:@{@"SID":GETShopId} success:^(id responseObject) {
        NSLog(@"-- %@",responseObject);
        NSInteger err = [[responseObject valueForKey:@"Err"]integerValue];
        
        if (err != 0) {
            [SVProgressHUD setInfoImage:[UIImage imageNamed:@"jiameng"]];
            [SVProgressHUD showInfoWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [SVProgressHUD dismissWithDelay:1];
            
        }else{
            [self.classArr removeAllObjects];
            NSArray *arr = [responseObject valueForKey:@"Category"];
            //一级菜单
            for (NSDictionary *dic in arr) {
                ClassIfModel *model = [[ClassIfModel alloc]initWithDic:dic];
                [self.classArr addObject:model];
            }
            [self.leftTableView reloadData];
 //判断是不是之前的shopId，如果shopId更改就重置默认选项
            //设置左侧tableView的默认选项
            if (isFirst) {
                NSIndexPath *defalutIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self tableView:_leftTableView didDeselectRowAtIndexPath:selIndexPath];
                [self tableView:_leftTableView didSelectRowAtIndexPath:defalutIndexPath];
                [self creatScondMenu];
            }
        }
    } filed:^(NSError *error) {
        
    }];
//  }
}

//获取分类的商品列表
- (void)netWorkingWithCID:(NSString* )cid{
//    NSLog(@"cid  %@",cid);
    [self.productArr removeAllObjects];
    [CQNetWorkTools GETWithURL:Getprolist par:@{@"SID":GETShopId,@"CID":cid}success:^(id responseObject) {
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0) {
            //失败
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }else{
            self.productArr = [ClassIfProductModel mj_objectArrayWithKeyValuesArray:[responseObject valueForKey:@"Products"]];
            self.rightTableView.hidden = NO;
        }
        [self.rightTableView reloadData];
    } filed:^(NSError *error) {
        
    }];
//    NSLog(@"end");
}
#pragma mark - SVProgressHUD
- (void)SVProgressHUDAction{
    //渐变而且禁止用户操作
    [SVProgressHUD showWithStatus:@"加载中..."];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

#pragma mark - 代码构建部分页面，二级头视图

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (!_hotBtnView) {
        _hotBtnView = [[UIView alloc]initWithFrame:CGRectMake (self.leftTableView.right,44,self.rightTableView.width, 40)];
        _hotBtnView.backgroundColor = XNColor(251, 251, 251, 1);
        _hotBtnView.hidden = YES;
    }
    [self.view addSubview:_hotBtnView];
    self.rightTableView.top = rightTop;
    self.rightTableView.height = rightHeight - self.hotBtnView.height;
    self.hotBtnView.left = self.leftTableView.right;
    //在数据很少的时候 避免显示多余的分割线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.leftTableView setTableFooterView:v];
    [self.rightTableView setTableFooterView:v];
}

//构建二级菜单
- (void)creatScondMenu{
    //创建二级菜单
    if (_classArr.count > 0) {
    //选中默认第一组
        if (isFirst) {
            ClassIfModel *model0 = [[ClassIfModel alloc]initWithDic:[self.classArr firstObject]];
            [self creatTwoBtn:model0];
        }
    }
}
//构建二级菜单按钮
- (void)creatTwoBtn:(ClassIfModel *)model{
    //清空数组
    [self.twoClassArr removeAllObjects];
    //清扫btn
    for (UIButton *btn in self.hotBtnView.subviews) {
        [btn removeFromSuperview];
    }
    //判断有木有二级分类
    if (model.SubCategory.count == 0) {
        self.hotBtnView.hidden = YES;
        self.rightTableView.top = self.marketBtn.bottom;
        self.rightTableView.height = rightHeight;
        rightTop = self.marketBtn.bottom;
    }else{
       
        self.hotBtnView.hidden = NO;
    for (NSDictionary *dic in model.SubCategory) {
        ClassIfModel *model = [[ClassIfModel alloc]initWithDic:dic];
        [self.twoClassArr addObject:model];
    }
        //先算行数
        NSInteger hang = self.twoClassArr.count / 4;
        if ((self.twoClassArr.count % 4) > 0) {
            hang = hang + 1;
        }
        // 设置计数器 num 当num = count时跳出循环
        // i：行数 j：列数
        NSInteger num = 0;
        for (NSInteger i = 0;  i < hang; i ++ ) {
            for (NSInteger j = 0; j < 4; j++) {
         
                if (num == self.twoClassArr.count) {
                    break;
                }
                
                UIButton *btn = [UIButton buttonWithType:0];
                btn.frame = CGRectMake(0 + (j * _rightTableView.width / 4 + 0.5) + 2, 0 + i * 35, _rightTableView.width / 4 - 7, 30);
                ClassIfModel *model = self.twoClassArr[num];
                [btn setTitle:[NSString stringWithFormat:@"%@",model.Name] forState:0];
//                [btn setBackgroundImage:[UIImage imageNamed:@"矩形-17-拷贝-7"] forState:UIControlStateSelected];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
                
                btn.layer.masksToBounds = YES;
                btn.layer.cornerRadius = 5;
                btn.layer.borderWidth = 1.0f;
                btn.layer.borderColor = [[UIColor whiteColor]CGColor];
                [btn.titleLabel setTextAlignment:NSTextAlignmentNatural];
                btn.tag = 10000 + model.Id;
                btn.titleLabel.font = [UIFont systemFontOfSize:15];
                if (FourInch) {
                    btn.titleLabel.font = [UIFont systemFontOfSize:13];
                }
                [btn setTitleColor:[UIColor grayColor] forState:0];
                [btn addTarget:self action:@selector(hotBtnAction:) forControlEvents:UIControlEventTouchUpInside];
                btn.backgroundColor = [UIColor whiteColor];
                [_hotBtnView addSubview:btn];
                
                if (num == 0) {
                    [btn setTitleColor:GDJGreenColor forState:0];
                    btn.layer.borderColor = [GDJColor(138,184,52) CGColor];
                }
                
                num ++ ;
            }
        }

     _hotBtnView.height = hang * 35;
     _hotBtnView.hidden = NO;
     
     rightTop = _hotBtnView.bottom;
     self.rightTableView.top = rightTop;
     self.rightTableView.height = rightHeight - self.hotBtnView.height;
  }
}
//二级菜单按钮触发
- (void)hotBtnAction:(UIButton *)btn{
    
    for (UIButton *btnn in _hotBtnView.subviews) {
        btnn.layer.borderColor = [[UIColor whiteColor]CGColor];
        [btnn setBackgroundColor:[UIColor whiteColor]];
        [btnn setTitleColor:[UIColor grayColor] forState:0];
    }
    [btn setTitleColor:GDJGreenColor forState:0];
    btn.layer.borderColor = [GDJColor(138,184,52) CGColor];
    NSString *cid = [NSString stringWithFormat:@"%ld",btn.tag - 10000];
    [self netWorkingWithCID:cid];
}
#pragma mark - 分类菜单
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.rightTableView == tableView) {
        return self.productArr.count;
    }
    return self.classArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        static NSString *lftIdentifer = @"leftCell";
        ClassIfCell *leftCell = [tableView dequeueReusableCellWithIdentifier:lftIdentifer];
        if (!leftCell) {
            leftCell = [[[NSBundle mainBundle]loadNibNamed:@"ClassIfCell" owner:nil options:nil]lastObject];
        }
        if (self.classArr.count > 0) {
            ClassIfModel *model = self.classArr[indexPath.row];
            leftCell.titleLabel.text = model.Name;
        }
      leftCell.selectionStyle = UITableViewCellSelectionStyleNone;
      leftCell.textLabel.textColor = [UIColor grayColor];
        
      return leftCell;
    }
   //右侧的
    static NSString *rightIdentifer = @"rightCell";
    RightTableViewCell *rightCell = [tableView dequeueReusableCellWithIdentifier:rightIdentifer];
    if (!rightCell) {
        rightCell = [[[NSBundle mainBundle]loadNibNamed:@"RightTableViewCell" owner:self options:nil]lastObject];
    }
    if (self.productArr.count > 0) {
         rightCell.model = self.productArr[indexPath.row];
    }
    rightCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return rightCell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _rightTableView) {
        return 120;
    }
        return 44;
}
#pragma mark - tableView点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _rightTableView) {
//      点击右侧按钮，push到商品页面
        if (!_commodityVC) {
            _commodityVC = [[CommodityViewController alloc]init];
        }
        ClassIfProductModel *model = self.productArr[indexPath.row];
        _commodityVC.ProductId = [NSString stringWithFormat:@"%d",model.Id];
        [self.navigationController pushViewController:_commodityVC animated:YES];
    }else{
//      点击左侧按钮
        ClassIfCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.picSel.hidden = NO;
        cell.titleLabel.textColor = GDJGreenColor;
        if (indexPath.row == 0) {
        }else{
            ClassIfCell *oneCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            oneCell.picSel.hidden = YES;
            oneCell.titleLabel.textColor = [UIColor blackColor];
        }
//        NSLog(@"classArr.count %@",self.classArr);
        //更换数据源并刷新rightTableView，更换头视图
        if (self.classArr.count > 0) {
            ClassIfModel *model = self.classArr[indexPath.row];
            //更换二级菜单
            [self netWorkingWithCID:[NSString stringWithFormat:@"%d",model.Id]];
            [self creatTwoBtn:model];
        }
        //保存之前的indexPath
        selIndexPath = indexPath;
    }
}
//取消上一个cell的选中状态
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTableView == tableView) {
        ClassIfCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.titleLabel.textColor = [UIColor blackColor];
        cell.picSel.hidden = YES;
    }
}

#pragma mark - 弹出商店页面
- (IBAction)marketBtn:(id)sender {
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        if (!_storeViewCollection) {
            _storeViewCollection = [[StoreViewController alloc]init];
        }
        [self.navigationController pushViewController:_storeViewCollection animated:YES];
    }
}
@end
